package scheduler

import (
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"go-fox-edge-iot-fastbee/remote"
	"go-fox-edge-iot-fastbee/service"
	"time"
)

type deviceSubscribeScheduler struct {
}

func (e *deviceSubscribeScheduler) scheduler() {
	for true {
		time.Sleep(1 * time.Second)
		if !commEntityManager.EntityManager.Initialized {
			continue
		}

		e.do()
	}
}
func (e *deviceSubscribeScheduler) do() {
	defer func() {
		if r := recover(); r != nil {
			commLogger.Console.Error(fmt.Sprintf("config() 捕获到异常:%v", r))
		}
	}()

	clientIds := make(map[string]interface{}, 0)
	entityList, err := commEntityManager.GetEntityMap(edgeEntity.Type.DeviceEntity.Type())
	if err != nil {
		return
	}

	for _, entity := range entityList {
		deviceEntity := entity.(*edgeEntity.DeviceEntity)

		// 取出注册参数
		productId := deviceEntity.ExtendParam[service.FastBeeService.ProductId]
		deviceNum := deviceEntity.ExtendParam[service.FastBeeService.DeviceNum]
		if productId == nil || productId == "" || deviceNum == nil || deviceNum == "" {
			continue
		}

		// 保存：计划创建的连接
		clientId := remote.RemoteCloud.BuildClientId(productId, deviceNum)
		clientIds[clientId] = nil

		// 订阅云端的控制命令
		remote.RemoteCloud.SubscribeTopic(deviceEntity.DeviceName, productId, deviceNum)
	}

	// 关闭配置无效的mqtt连接
	remote.RemoteCloud.CloseNotExist(clientIds)
}
